package com.foryou.swkj.core.util;


import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

/**
     * <p> 类说明 ：text/application-json</p>
     * @author Dante Fung
     * Date: 2016年10月8日
     * @version 1.01
     *
     */
    public class MyHttpUtils {
        
        private static final Logger logger = LoggerFactory.getLogger(MyHttpUtils.class);

        public static final String CONTENT_TYPE_APPLICATION_XML = "application/xml";
        public static final String CONTENT_TYPE_TEXT_XML = "text/xml";

        public static CloseableHttpClient createDefaultSsLClient() {
            try {
                SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                        new TrustStrategy() {
                            // 信任所有
                            public boolean isTrusted(X509Certificate[] chain, String authType)
                                    throws CertificateException {
                                return true;
                            }
                        }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
                return HttpClients.custom().setSSLSocketFactory(sslsf).build();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    
        public static  byte[] httpsGet0(String url) {
            logger.info(" begin to create Default SSL Client now !!! ");
            CloseableHttpClient httpClient = createDefaultSsLClient();
            logger.info(" create Default SSL Client Succesfully !!! " + httpClient);
            HttpGet get = new HttpGet();
            try {
                get.setURI(new URI(url));
                HttpResponse response = httpClient.execute(get);
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (null == entity) {
                    return new byte[0];
                }
                byte[] datas = IOUtils.toByteArray(entity.getContent());
                EntityUtils.consume(entity); // Consume response content
                return datas;
            } catch (Exception ex) {
                get.abort();
                throw new RuntimeException(ex);
            }
        }
    
        public static byte[] httpsPost0(String url, String content, String charsetName) throws UnsupportedEncodingException {
            return httpsPost0(url, new StringEntity(content, charsetName));
        }
        public static byte[] httpsPost0(String url, String content, String charsetName, String contentType) throws UnsupportedEncodingException {
            return httpsPost0(url, new StringEntity(content, charsetName),contentType);
        }

        public static byte[] httpsPost0(String url, List<? extends NameValuePair> pairs, String charset, String contentType) {
            try {
                return httpsPost0(url, new UrlEncodedFormEntity(pairs, charset), contentType);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        public static byte[] httpsPost0(String url, List<? extends NameValuePair> pairs, String charset) {
            try {
                return httpsPost0(url, new UrlEncodedFormEntity(pairs, charset));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }

        public static byte[] httpsPost0(String url, HttpEntity content, String contentType) {
            CloseableHttpClient httpClient = createDefaultSsLClient();
            HttpPost post = new HttpPost();
            try {
                post.setURI(new URI(url));
                post.setEntity(content);
                post.setHeader("Content-Type", contentType);
                HttpResponse response = httpClient.execute(post);
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (null == entity) {
                    return new byte[0];
                }
                byte[] datas = IOUtils.toByteArray(entity.getContent());
                EntityUtils.consume(entity); // Consume response content
                return datas;
            } catch (Exception ex) {
                post.abort();
                throw new RuntimeException(ex);
            }
        }
        public static byte[] httpsPost0(String url, HttpEntity content) {
            CloseableHttpClient httpClient = createDefaultSsLClient();
            HttpPost post = new HttpPost();
            try {
                post.setURI(new URI(url));
                post.setEntity(content);
                post.setHeader("Content-Type", "application/json");
                HttpResponse response = httpClient.execute(post);
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (null == entity) {
                    return new byte[0];
                }
                byte[] datas = IOUtils.toByteArray(entity.getContent());
                EntityUtils.consume(entity); // Consume response content
                return datas;
            } catch (Exception ex) {
                post.abort();
                throw new RuntimeException(ex);
            }
        }

        public static String httpsGet(String url, String charsetName) {
            try {
                logger.info( String.format("http get infomation--> url:%s, charsetName:%s", url, charsetName) );
                return new String(httpsGet0(url), charsetName);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    
        public static String httpsPost(String url, String content, String charsetName) {
            try {
                return new String(httpsPost0(url, content, charsetName), charsetName);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }

        public static String httpsPost(String url, String content, String charsetName, String contentType) {
            try {
                return new String(httpsPost0(url, content, charsetName, contentType), charsetName);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }

        public String httpsPost(String url, List<? extends NameValuePair> pairs, String charset) {
            try {
                return new String(httpsPost0(url, pairs, charset), charset);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        public String httpsPost(String url, List<? extends NameValuePair> pairs, String charset, String contentType) {
            try {
                return new String(httpsPost0(url, pairs, charset, contentType), charset);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
    }
